from sqlalchemy.ext.asyncio import AsyncSession
from module_admin.entity.vo.employee_payment_vo import EmployeePaymentQueryModel
from module_admin.entity.vo.employee_payment_vo import EmployeePaymentModel
from module_admin.entity.do.employee_payment_do import EmployeePayment
from module_admin.entity.do.employee_do import EmployeeInfo
from sqlalchemy import select, or_
from utils.page_util import PageUtil
from utils.log_util import logger

class EmployeePaymentDao:
    """
    员工支出模块数据库操作层
    """

    @classmethod
    async def get_payment_list(cls, db: AsyncSession, page_object: EmployeePaymentQueryModel, is_page: bool = False):
        """
        根据查询参数获取员工支出列表信息

        :param db: orm对象
        :param page_object: 不分页查询参数对象
        :param is_page: 是否开启分页
        :return: 员工支出列表信息对象
        """
        try:
            # 构建基础查询
            query = (
                select(
                    EmployeePayment.id,
                    EmployeePayment.employee_id,
                    EmployeePayment.payment_date,
                    EmployeePayment.payment_amount,
                    EmployeePayment.del_flag,
                    EmployeePayment.create_by,
                    EmployeePayment.create_time,
                    EmployeePayment.update_by,
                    EmployeePayment.update_time,
                    EmployeeInfo.name
                )
                .join(EmployeeInfo, EmployeePayment.employee_id == EmployeeInfo.id)
            )
            
            # 添加where条件
            where_conditions = []
            
            # 添加del_flag条件
            where_conditions.append(or_(EmployeePayment.del_flag == '0', EmployeePayment.del_flag.is_(None)))
            
            # 只有当payment_amount不为0时才添加条件
            if page_object.payment_amount != 0:
                where_conditions.append(EmployeePayment.payment_amount == page_object.payment_amount)
            
            # 添加其他条件
            if page_object.id is not None:
                where_conditions.append(EmployeePayment.id == page_object.id)
            if page_object.employee_id is not None:
                where_conditions.append(EmployeePayment.employee_id == page_object.employee_id)
            if page_object.payment_date:
                where_conditions.append(EmployeePayment.payment_date == page_object.payment_date)
            if page_object.name:
                where_conditions.append(EmployeeInfo.name.like(f"%{page_object.name}%"))
            
            # 应用where条件
            if where_conditions:
                query = query.where(*where_conditions)
            
            # 添加排序
            query = query.order_by(EmployeePayment.id)
            
            # 记录SQL查询
            logger.info(f"SQL Query: {query}")
            
            # 执行查询
            result = await db.execute(query)
            rows = result.all()
            
            # 打印查询结果的结构
            logger.info(f"Query result structure: {type(rows)}")
            if rows:
                logger.info(f"First row structure: {type(rows[0])}")
                logger.info(f"First row content: {rows[0]}")
            
            # 转换为字典列表
            result = []
            for row in rows:
                # 打印每行的结构
                logger.info(f"Row type: {type(row)}")
                logger.info(f"Row content: {row}")
                
                # 根据实际的数据结构处理
                if isinstance(row, dict):
                    payment_dict = {
                        "id": row.get('id'),
                        "employeeId": row.get('employee_id'),
                        "name": row.get('name'),
                        "paymentDate": row.get('payment_date').strftime("%Y-%m-%d") if row.get('payment_date') else None,
                        "paymentAmount": row.get('payment_amount'),
                        "delFlag": row.get('del_flag'),
                        "createBy": row.get('create_by'),
                        "createTime": row.get('create_time').strftime("%Y-%m-%dT%H:%M:%S") if row.get('create_time') else None,
                        "updateTime": row.get('update_time').strftime("%Y-%m-%dT%H:%M:%S") if row.get('update_time') else None
                    }
                else:
                    # 如果是元组或其他类型，尝试直接访问属性
                    payment_dict = {
                        "id": getattr(row, 'id', None),
                        "employeeId": getattr(row, 'employee_id', None),
                        "name": getattr(row, 'name', None),
                        "paymentDate": getattr(row, 'payment_date', None).strftime("%Y-%m-%d") if getattr(row, 'payment_date', None) else None,
                        "paymentAmount": getattr(row, 'payment_amount', None),
                        "delFlag": getattr(row, 'del_flag', None),
                        "createBy": getattr(row, 'create_by', None),
                        "createTime": getattr(row, 'create_time', None).strftime("%Y-%m-%dT%H:%M:%S") if getattr(row, 'create_time', None) else None,
                        "updateTime": getattr(row, 'update_time', None).strftime("%Y-%m-%dT%H:%M:%S") if getattr(row, 'update_time', None) else None
                    }
                result.append(payment_dict)
            
            return result
        except Exception as e:
            logger.error(f"Error in get_payment_list: {str(e)}")
            raise

    @classmethod
    async def add_payment(cls, db: AsyncSession, payment: EmployeePaymentModel):
        """
        新增员工支出信息
        :param db: orm对象
        :param payment: 员工支出信息对象
        :return: 新增员工支出的主键ID或完整对象
        """
        payment_dict = {
            'employee_id': payment.employee_id,
            'payment_date': payment.payment_date,
            'payment_amount': payment.payment_amount,
            'del_flag': payment.del_flag,
            'create_by': payment.create_by,
            'create_time': payment.create_time,
            'update_by': payment.update_by,
            'update_time': payment.update_time
        }
        db_payment = EmployeePayment(**payment_dict)
        db.add(db_payment)
        await db.flush()
        return db_payment

    @classmethod
    async def update_payment(cls, db: AsyncSession, payment: EmployeePaymentModel):
        """
        修改员工支出信息
        :param db: orm对象
        :param payment: 员工支出信息对象
        :return: 修改后的员工支出对象
        """
        payment_dict = {
            'employee_id': payment.employee_id,
            'payment_date': payment.payment_date,
            'payment_amount': payment.payment_amount,
            'update_by': payment.update_by,
            'update_time': payment.update_time
        }
        # 移除None值的键
        payment_dict = {k: v for k, v in payment_dict.items() if v is not None}
        
        query = (
            select(EmployeePayment)
            .where(EmployeePayment.id == payment.id)
        )
        result = await db.execute(query)
        db_payment = result.scalar_one_or_none()
        
        if db_payment:
            for key, value in payment_dict.items():
                setattr(db_payment, key, value)
            await db.flush()
        
        return db_payment

    @classmethod
    async def delete_payment(cls, db: AsyncSession, payment_id: int, update_by: str = None):
        """
        删除员工支出信息（逻辑删除）
        :param db: orm对象
        :param payment_id: 员工支出ID
        :param update_by: 更新者
        :return: 是否删除成功
        """
        query = (
            select(EmployeePayment)
            .where(EmployeePayment.id == payment_id)
        )
        result = await db.execute(query)
        db_payment = result.scalar_one_or_none()
        
        if db_payment:
            db_payment.del_flag = '2'
            if update_by:
                db_payment.update_by = update_by
            await db.flush()
            return True
        return False 